﻿using System;
using ThunderRoad;
using UnityEngine;

namespace BBYScripts
{
    public class PreciseThrow : MonoBehaviour
    {
        public Item item;
        public float fovAngleHorizontal = 60f;
        public float fovAngleVertical = 60f;
        public float fovDistance = 50f;
        public int rayCountHorizontal = 30;
        public int rayCountVertical = 4;
        private LayerMask _targetMask;
        private float _angleStepHorizontal;
        private float _angleStepVertical;
        private float _halfFOVVertical;
        private float _halfFOVHorizontal;
        private Transform _itemFlyDirRef;
        private Rigidbody _rigidbody;
 
        private void Start()
        {
            if (!item)
            {
                Debug.LogError(this.name + ": No item selected");
                return;
            }

            _rigidbody = item.GetComponent<Rigidbody>();
            if (_rigidbody == null)
            {
                Debug.LogError(this.name + ": No rigidbody attached");
                return;
            }

            _targetMask = LayerMask.GetMask("BodyLocomotion", "NPC");

            // 计算水平和垂直方向上每条射线之间的角度差
            _angleStepHorizontal = fovAngleHorizontal / rayCountHorizontal;
            _angleStepVertical = fovAngleVertical / rayCountVertical;
            _halfFOVHorizontal = fovAngleHorizontal / 2;
            _halfFOVVertical = fovAngleVertical / 2;
            _itemFlyDirRef = item.flyDirRef;
            item.OnThrowEvent += i =>
            {
                if (PlayerControl.GetHand(Side.Right).usePressed)
                {
                    AutoNavRun();
                }
            };
            // item.OnFlyStartEvent += i => AutoNavRun();
            item.OnFlyEndEvent += i => FlyEnd();
        }

        public void FlyEnd()
        {
        }


        public void AutoNavRun()
        {
            if (!Player.local)
            {
                return;
            }

            RaycastHit hit;
            if (!FindForwardHit(out hit))
            {
                Debug.Log("未发现敌人！");
                return;
            }

            Debug.Log("发现" + hit.collider.gameObject);
            var pi = hit.collider.gameObject.GetComponentInParent<Item>();
            Debug.Log("hit item:" + (pi == null));
            // 计算击中位置和玩家位置之间的向量
            var throwDirection = hit.point - item.transform.position;
            // 归一化这个向量
            throwDirection.Normalize();
            Debug.Log("throwDirection: " + throwDirection);
            Debug.Log("Target:" + hit.point);
            // 施加力，这里你可以根据需要调整力的大小
            _rigidbody.AddForce(throwDirection * 40, ForceMode.Impulse);
        }

        private bool FindForwardHit(out RaycastHit hit)
        {
            var origin = Player.local.head.transform.position + Player.local.head.transform.forward;
            // 执行射线检测
            int i1;
            for (var i = i1 = rayCountVertical / 2; i >= 0; i--, i1++)
            {
                int j1;
                for (var j = j1 = rayCountHorizontal / 2; j >= 0; j--, j1++)
                {
                    if (DoCheck(origin, i, j, out hit) || !(i == i1 && j == j1) && DoCheck(origin, i1, j1, out hit))
                    {
                        return true;
                    }
                }
            }

            hit = new RaycastHit();
            return false;
        }

        private bool DoCheck(Vector3 origin, int i, int j, out RaycastHit hit)
        {
            // 计算当前射线的水平和垂直角度
            var angleHorizontal = -_halfFOVHorizontal + _angleStepHorizontal * j;
            var angleVertical = -_halfFOVVertical + _angleStepVertical * i;
            // 创建一个水平方向上的射线方向
            var forward = Player.local.head.transform.forward;
            var horizontalRayDirection = Quaternion.AngleAxis(angleHorizontal, Vector3.up) * forward;
            // 应用垂直旋转
            var rayDirection = Quaternion.AngleAxis(angleVertical, Vector3.right) * horizontalRayDirection;

            // 发射射线
            return Physics.Raycast(origin, rayDirection, out hit, fovDistance, _targetMask);
        }
    }
}